package cn.rkylin.oms.order.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TradeGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.TradeGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;

import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.oms.order.domain.Order;
import cn.rkylin.oms.order.domain.taobao.TopOrder;
import cn.rkylin.oms.order.domain.taobao.TopTrade;
import cn.rkylin.oms.order.domain.taobao.TopTradeOrder;
import cn.rkylin.oms.order.vo.Logistic_service_tag;
import cn.rkylin.oms.order.vo.Logistics_tag;
import cn.rkylin.oms.order.vo.Promotion_detail;
import cn.rkylin.oms.order.vo.TaoBaoOrder;
import cn.rkylin.oms.order.vo.TaoBaoResponse;
import cn.rkylin.oms.order.vo.Trade;
import cn.rkylin.oms.order.vo.TradeFullInfo;
import cn.rkylin.oms.order.vo.TradesSoldGetResponseVO;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.vo.ShopVO;

@Service("taoBaoOrderApiVisitor")
public class TaoBaoOrderApiVisitor extends OrderVisitor {
    private static final Log logger = LogFactory.getLog(TaoBaoOrderApiVisitor.class);
    private static final long pageSize = 100L;
    /**
     * 数据库访问对象
     */
    @Autowired
    private IDataBaseFactory dao;
    
    public void finalize() throws Throwable {
        super.finalize();
    }

    
    /**
     * 构造函数
     */
    public TaoBaoOrderApiVisitor(){
        //
    }
    
    @Override
    public int getOrderList(Date startTime, Date endTime, Map<String, String> paramMap) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Order getOrder(String orderNumber, Map<String, String> paramMap) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void saveOrder() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public List<Order> getOrderList(Map<String, String> paramMap) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Map<String, Object> getOrderObject(String tid, Shop shopVO) {
        // TODO Auto-generated method stub
        return null;
    }
    
    
    @Override
    public Map<String, Object> getOrderObject(Map<String, Object> paramMap) {
        return getTradeFromTaoBao(paramMap);
    }
    
    /**
     * 利用jdbc直接访问聚石塔的表取得返回的结果集
     * @param paramMap
     * @return 里面分别保存trade和order的数据
     * @throws ParseException 
     */
    private Map<String,Object> getTradeFromTaoBao(Map<String,Object> paramMap){
        Map<String,Object> map = null;                          //返回值，里面分别保存trade和order的数据
        
        //如果店铺名称没有，就取消操作
        ShopVO shopVO = (ShopVO)paramMap.get("shop");
        if (shopVO==null){
            return null;
        }
      
        //按照条件取得tid数组
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = null;
        Date end = null;
        try{
            start = paramMap.get("startTime")!=null?sdf.parse((String)paramMap.get("startTime")):null;
            end = paramMap.get("endTime")!=null?sdf.parse((String)paramMap.get("endTime")):null;    
        } catch(Exception e){
            e.printStackTrace();
            
        }
        
        List<String> tids = getTids(start,end,shopVO,1L);
        
        //根据tid取得订单信息
        List<TaoBaoOrder> list = new ArrayList<TaoBaoOrder>();
        if (tids!=null && tids.size() > 0){
            for (int i = 0 ; i < tids.size() ; i++){
                List<TaoBaoOrder> taobaoOrders = getTaobaoOrders(shopVO , tids.get(i));
                if (taobaoOrders!=null && taobaoOrders.size()>0){
                    list.addAll(taobaoOrders);
                }
            }
        }
        map = getTopVO(list);
        
      return map;
    }
    
    /**
     * 根据json的相关内容转换成为oms_top_trade的bean
     * @param trade
     * @return
     */
    private TopTrade getTopTrade(Trade trade , String tradeId) {
        TopTrade topTrade = new TopTrade();
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            topTrade.setTopTradeId(tradeId);
            topTrade.setAdjustFee(trade.getAdjust_fee());
//          (trade.getAlipay_id());
//          (trade.getAlipay_no());
//          (trade.getAlipay_point());
//          (trade.getAvailable_confirm_fee());
//          (trade.getBuyer_alipay_no());
//          (trade.getBuyer_area());
//          (trade.getBuyer_email());
            topTrade.setBuyerCodFee(trade.getBuyer_cod_fee());
            topTrade.setBuyerNick(trade.getBuyer_nick());
//          (trade.getBuyer_obtain_point_fee());
            topTrade.setBuyerRate("true".equals(trade.getBuyer_rate())?1:0);
//          (trade.getCod_fee());
//          (trade.getCod_status());
//          (trade.getCommission_fee());
            topTrade.setCreated(sdf.parse(trade.getCreated()));
            topTrade.setDiscountFee(trade.getDiscount_fee());
//          topTrade.setHasPostFee(trade.getHas_post_fee()); //json里面的值是true，但是数据库对应的是bigdecimal，两者转换类型出问题
//          (trade.getIs_3D());
//          (trade.getIs_brand_sale());
//          (trade.getIs_force_wlb());
//          (trade.getIs_lgtype());
//          (trade.getIs_part_consign());
//          (trade.getIs_wt());
            topTrade.setModified(sdf.parse(trade.getModified()));
            topTrade.setConsignTime(trade.getConsign_time()!=null?sdf.parse(trade.getConsign_time()):null);
            topTrade.setNum(trade.getNum());
//          (trade.getNum_iid());
            topTrade.setPayTime(trade.getPay_time()!=null?sdf.parse(trade.getPay_time()):null);
            topTrade.setPayment(trade.getPayment());
//          (trade.getPcc_af());
            topTrade.setPicPath(trade.getPic_path());
//          (trade.getPoint_fee());
            topTrade.setPostFee(trade.getPost_fee());
            topTrade.setPrice(trade.getPrice());
//          (trade.getReal_point_fee());
            topTrade.setReceivedPayment(trade.getReceived_payment());
            topTrade.setReceiverAddress(trade.getReceiver_address());
            topTrade.setReceiverCity(trade.getReceiver_city());
            topTrade.setReceiverDistrict(trade.getReceiver_district());
            topTrade.setReceiverMobile(trade.getReceiver_mobile());
            topTrade.setReceiverName(trade.getReceiver_name());
            topTrade.setReceiverState(trade.getReceiver_state());
            topTrade.setReceiverZip(trade.getReceiver_zip());
//          (trade.getSeller_alipay_no());
//          (trade.getSeller_can_rate());
//          (trade.getSeller_cod_fee());
//          (trade.getSeller_email());
            topTrade.setSellerFlag(trade.getSeller_flag());
//          (trade.getSeller_mobile());
//          (trade.getSeller_name());
            topTrade.setSellerNick(trade.getSeller_nick());
            topTrade.setSellerRate("true".equals(trade.getSeller_rate())?Integer.valueOf(1):Integer.valueOf(0));
            topTrade.setShippingType(trade.getShipping_type());
//          (trade.getSnapshot_url());
            topTrade.setStatus(trade.getStatus());
            topTrade.setTid(trade.getTid());
            topTrade.setTitle(trade.getTitle());
            topTrade.setTotalFee(trade.getTotal_fee());
            topTrade.setTradeFrom(trade.getTrade_from());
            topTrade.setType(trade.getType());
        } catch(Exception ex){
            ex.printStackTrace();
             logger.error(ex.getMessage(), ex);
            return null;
        }
        
        return topTrade;
    }
    
    /**
     * 保存数据到oms_top_trade
     * @param list
     * @return
     */
    private int saveTopTrade(TopTrade topTrade){
        try {
            //如果存在的场合
            TopTrade trade = (TopTrade) dao.find("selectByTidTopTrade", topTrade.getTid().toString());
            Date date = new Date();
            if (trade == null) {
                topTrade.setCreateTime(date);
                topTrade.setUpdateTime(date);
                dao.insert("insertSelectiveTopTrade", topTrade);
            } else {
                if (topTrade.getModified().compareTo(trade.getModified())>0){
                    topTrade.setUpdateTime(date);
                    topTrade.setTopTradeId(trade.getTopTradeId());
                    dao.update("updateByTidSelectiveTopTrade", topTrade);
                    TopOrder topOrder = new TopOrder();
                    topOrder.setTid(topTrade.getTid());
                    dao.delete("deleteByTidTopOrder", topOrder);
                }
            }
        } catch (Exception ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
            return 0;
        }
        return 1;
    }
    
    /**
     * 根据json的相关内容转换成为oms_top_order的bean
     * @param trade
     * @return
     */
    private List<TopOrder> getTopOrder(Trade trade,String tradeId,Long tid) {
        List<TopOrder> list = new ArrayList<TopOrder>();
        List<cn.rkylin.oms.order.vo.Order> listOrder = trade.getOrders();
        //日期格式化
        try{
            if (listOrder==null || listOrder.size()<=0){
                return null; 
            }
            
            for (int i = 0 ; i < listOrder.size() ; i++){
                TopOrder topOrder = new TopOrder();
                topOrder.setTopTradeId(tradeId);
                topOrder.setTid(tid);
                topOrder.setTopOrderId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                topOrder.setAdjustFee(listOrder.get(i).getAdjust_fee());
                topOrder.setBuyerRate("true".equals(listOrder.get(i).getBuyer_rate())?Integer.valueOf(1):Integer.valueOf(0));
                topOrder.setCid(listOrder.get(i).getCid());
                topOrder.setDiscountFee(listOrder.get(i).getDiscount_fee());
                topOrder.setIsDaixiao("true".equals(listOrder.get(i).getIs_daixiao())?Integer.valueOf(1):Integer.valueOf(0));
                topOrder.setIsOversold("true".equals(listOrder.get(i).getIs_oversold())?Integer.valueOf(1):Integer.valueOf(0));
                topOrder.setNum(listOrder.get(i).getNum());
                topOrder.setNumIid(listOrder.get(i).getNum_iid());
                topOrder.setOid(listOrder.get(i).getOid());
                topOrder.setOrderFrom(listOrder.get(i).getOrder_from());
                topOrder.setOuterIid(listOrder.get(i).getOuter_iid());
                topOrder.setOuterSkuId(listOrder.get(i).getOuter_sku_id());
                topOrder.setPartMjzDiscount(listOrder.get(i).getPart_mjz_discount());
                topOrder.setPayment(listOrder.get(i).getPayment());
                topOrder.setPicPath(listOrder.get(i).getPic_path());
                topOrder.setPrice(listOrder.get(i).getPrice());
                topOrder.setRefundStatus(listOrder.get(i).getRefund_status());
                topOrder.setSellerRate("true".equals(listOrder.get(i).getSeller_rate())?Integer.valueOf(1):Integer.valueOf(0));
                topOrder.setSellerType(listOrder.get(i).getSeller_type());
                topOrder.setSkuId(listOrder.get(i).getSku_id()==null?0:listOrder.get(i).getSku_id());
                topOrder.setSkuPropertiesName(listOrder.get(i).getSku_properties_name());
                topOrder.setSnapshotUrl(listOrder.get(i).getSnapshot_url());
                topOrder.setStatus(listOrder.get(i).getStatus());
                topOrder.setTitle(listOrder.get(i).getTitle());
                topOrder.setTotalFee(listOrder.get(i).getTotal_fee());
                list.add(topOrder);
            }

        } catch(Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
            return null;
        }
        return list;
    }
    
    /**
     * 将解析生成的数据对应到oms_top_trade，oms_top_order表的VO中，并且保存
     * @param list
     * @return
     */
    private Map<String,Object> getTopVO (List<TaoBaoOrder> list){
        Map<String,Object> map = new HashMap<String, Object>();
        if (list == null || list.size() <=0){
            return null;
        }
        
        List<TopTradeOrder> listTopTradeOrder = new ArrayList<TopTradeOrder>(); 
        //循环json的结果集
        for (int i = 0 ; i < list.size() ; i++){
            TaoBaoOrder taoBaoOrder = list.get(i);
            if (taoBaoOrder!=null && taoBaoOrder.getTaoBaoResponse()!=null && taoBaoOrder.getTaoBaoResponse().getTrade_fullinfo_get_response()!=null){
                //取得trade
                Trade trade = taoBaoOrder.getTaoBaoResponse().getTrade_fullinfo_get_response().getTrade();
                TopTradeOrder topTradeOrder = new TopTradeOrder();
                
                //生成oms_top_trade的主键
                String tradeId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
                //Trade转换成为oms_top_trade的VO
                TopTrade topTrade = getTopTrade(trade,tradeId);
                if (saveTopTrade(topTrade) == 1){
                    topTradeOrder.setTopTrade(topTrade);    
                    
                    //转黄成为oms_top_order的VO
                    List<TopOrder> topOrders = getTopOrder(trade,tradeId,topTrade.getTid());
                    if (saveTopOrder(topOrders)>0){
                        topTradeOrder.setListTopOrder(topOrders);
                        listTopTradeOrder.add(topTradeOrder);
                    }
                    
                }
            }
            
        }

        //生成返回值
        map.put("tradeOrder", listTopTradeOrder);
        return map;
    }
    
    /**
     * 保存数据到oms_top_order
     * @param list
     * @return
     */
    private int saveTopOrder(List<TopOrder> list){
        if (list==null || list.size()<=0){
            return 0;
        }
        
        for (int i = 0 ; i < list.size() ; i++){
            TopOrder topOrder = list.get(i);
            Date date = new Date();
            topOrder.setCreateTime(date);
            topOrder.setUpdateTime(date);
            try {
            dao.insert("insertSelectiveTopOrder", topOrder);
            } catch (Exception ex) {
                // TODO Auto-generated catch block
                ex.printStackTrace();
                logger.error(ex.getMessage(), ex);
            }
        }
        
        return list.size();
    }
    
    private List<TaoBaoOrder> getTaobaoOrders(ShopVO shopVO , String tid){
        List<TaoBaoOrder> list = new ArrayList<TaoBaoOrder>();  //解析检索得到的json
        try {
            TaoBaoOrder taoBaoOrder = new TaoBaoOrder();
            
            TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
            TradeGetRequest req = new TradeGetRequest();
            req.setFields("adjust_fee,alipay_id,alipay_no,alipay_point,available_confirm_fee,buyer_alipay_no,buyer_area,"
                    + "buyer_cod_fee,buyer_email,buyer_nick,buyer_obtain_point_fee,buyer_rate,cod_fee,cod_status,"
                    + "commission_fee,created,discount_fee,has_post_fee,is_3D,is_brand_sale,is_force_wlb,is_lgtype,"
                    + "is_part_consign,is_wt,modified,num,num_iid,orders,pay_time,payment,pcc_af,pic_path,point_fee,"
                    + "post_fee,price,promotion_details,real_point_fee,received_payment,receiver_address,receiver_city,"
                    + "receiver_district,receiver_mobile,receiver_name,receiver_state,receiver_zip,seller_alipay_no,"
                    + "seller_can_rate,seller_cod_fee,seller_email,seller_flag,seller_mobile,seller_name,seller_nick,"
                    + "seller_rate,service_tags,shipping_type,snapshot_url,status,tid,title,total_fee,trade_from,type");
            req.setTid(Long.valueOf(tid));
            TradeGetResponse rsp = client.execute(req, shopVO.getSessionKey());
            System.out.println(rsp.getBody());
            
            taoBaoOrder.setTaoBaoResponse(getObjectFromJson(rsp.getBody(),"trade_get_response"));
            list.add(taoBaoOrder);
           
        } catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
        }
        return list;
    }
    
    private List<String> getTids(Date start , Date end , ShopVO shopVO,long pageIndex){
        List<String> tids = new ArrayList<String>();
        try {
            TaobaoClient client = new DefaultTaobaoClient(shopVO.getApiUrl(), shopVO.getAppKey(), shopVO.getAppSecret());
            TradesSoldGetRequest req = new TradesSoldGetRequest();
            req.setFields("tid");
            if (start!=null){
                req.setStartCreated(start);
            }
            if (end!=null){
                req.setEndCreated(end);
            }
            req.setUseHasNext(true);
            req.setPageNo(pageIndex);
            req.setPageSize(pageSize);
//            req.setType("fixed,auction,guarantee_trade,step,independent_simple_trade,independent_shop_trade,auto_delivery,ec,cod,game_equipment,shopex_trade,netcn_trade,external_trade,instant_trade,b2c_cod,hotel_trade,super_market_trade,super_market_cod_trade,taohua,waimai,o2o_offlinetrade,nopaid,step,eticket,tmall_i18n,nopaid,insurance_plus,finance,pre_auth_type,lazada");
            TradesSoldGetResponse rsp = client.execute(req, shopVO.getSessionKey());
            TradesSoldGetResponseVO vo =  getTids(rsp.getBody());
            System.out.println(rsp.getBody());
            List<Trade> list = vo.getTrades();
            if (list!=null && list.size()>0){
                for (int i = 0 ; i < list.size() ; i++){
                    tids.add(list.get(i).getTid().toString());
                }
            }
            pageIndex++;
            if ("true".equals(vo.getHas_next())){
                tids.addAll(getTids(start,end,shopVO,pageIndex));
            }
            
        } catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
       }
        return tids;
    }
    
    private TradesSoldGetResponseVO getTids(String json){
        JSONObject object = JSON.parseObject(json).getJSONObject("trades_sold_get_response");
        List<Trade> trades = new ArrayList<Trade>();
      //解析trades数组
        if (object.getJSONObject("trades")!=null){
            JSONArray tradeArray = object.getJSONObject("trades").getJSONArray("trade");
            
            if(null != tradeArray){
                trades = JSON.parseArray(tradeArray.toJSONString(), Trade.class);
            }
            
            object.remove("trades");
        }
        TradesSoldGetResponseVO vo = JSON.parseObject(object.toJSONString(), TradesSoldGetResponseVO.class);
        vo.setTrades(trades);
        
        return vo;
    }
    
    /**
     * json解析成为对象，由于json中含有数组，所以要特殊处理
     * @param json
     * @return
     */
    private TaoBaoResponse getObjectFromJson(String json,String title){
        JSONObject object = JSON.parseObject(json).getJSONObject(title).getJSONObject("trade");
        //解析orders数组
        JSONArray orderArray = object.getJSONObject("orders").getJSONArray("order");
        List<cn.rkylin.oms.order.vo.Order> orderList = new ArrayList<cn.rkylin.oms.order.vo.Order>();
        if(null != orderArray){
            orderList = JSON.parseArray(orderArray.toJSONString(), cn.rkylin.oms.order.vo.Order.class);
        }
        object.remove("orders");
        
        //解析promotion_details数组
        JSONArray promotionArray = object.getJSONObject("promotion_details")==null?null:object.getJSONObject("promotion_details").getJSONArray("promotion_detail");
        List<Promotion_detail> promotionList = new ArrayList<Promotion_detail>();
        if(null != promotionArray){
            promotionList = JSON.parseArray(promotionArray.toJSONString(), Promotion_detail.class);
        }
        object.remove("promotion_details");
        
        //解析service_tags数组(数组里面套数组的情况)
        JSONArray serviceArray = object.getJSONObject("service_tags")==null?null:object.getJSONObject("service_tags").getJSONArray("logistics_tag");
        List<Logistics_tag> serviceList = new ArrayList<Logistics_tag>();//logistic_service_tag_list
        if (serviceArray!=null){
            for(int i=0; i<serviceArray.size(); i++){
                JSONObject entityObj = serviceArray.getJSONObject(i);
                JSONArray logisticServiceArray = entityObj.getJSONObject("logistic_service_tag_list").getJSONArray("logistic_service_tag");
                List<Logistic_service_tag> logisticServiceList = new ArrayList<Logistic_service_tag>();
                if(null != logisticServiceArray){
                    logisticServiceList = JSON.parseArray(logisticServiceArray.toJSONString(), Logistic_service_tag.class);
                }
                entityObj.remove("logistic_service_tag_list");
                Logistics_tag logistics_tag = JSON.parseObject(entityObj.toJSONString(), Logistics_tag.class);
                serviceList.add(logistics_tag);
            }
        }
        object.remove("service_tags");
        
        //将数组的json对应的对象加入
        Trade trade = JSON.parseObject(object.toJSONString(), Trade.class);
        if(orderList!=null && orderList.size()>0){
            trade.setOrders(orderList); 
        }
        if (promotionList!=null && promotionList.size()>0){
            trade.setPromotion_details(promotionList);  
        }
        if (serviceList!=null && serviceList.size()>0){
            trade.setService_tags(serviceList); 
        }
        TaoBaoResponse taoBaoResponse = new TaoBaoResponse();
        TradeFullInfo tradeFullInfo = new TradeFullInfo();
        tradeFullInfo.setTrade(trade);
        taoBaoResponse.setTrade_fullinfo_get_response(tradeFullInfo);
        
        return taoBaoResponse;
    }


    @Override
    public Map<String, Object> consign(Map<String, Object> paramMap) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public void getOrderObjectList(Map<String, Object> paramMap, Integer startRow,Integer endRow, List<TaoBaoOrder> loopList) {
        // TODO Auto-generated method stub
    }
}
